﻿dojo.provide("dojot.comment.Comment");
dojo.experimental("dojot.comment.Comment");
dojo.require("dojox.dtl.html");
dojo.require("dojox.dtl.Context");
dojo.require("dojot.util.MemoryPageList");
dojo.require("dojo.i18n");
dojo.requireLocalization("dojot", "common");
dojo.requireLocalization("dojot", "comment");

var picCommentTemplate = {data: { 
	"identifier": "picId",
	"items": []
}}
dojo.declare("dojot.comment.Comment",null,
	{
	albumId:0,
	picId:0,
	reviewNode:null,
	commentsStore:null,
	tplContext:null,
	tpl:null,
	_messages:null,
	commentTextArea:null,
	commentListUrl:"",
	addCommentUrl:"",
	delCommentUrl:"",
	submitBtnId:"submitCommentBt",
	emptyCommentErrorInfo:"",
	overlengthCommentErrorInfo:"",
	forbiddenCommentErrorInfo: "",
	errorInfo:"",
	viewId:"",
	ownerId:"",
	isAdmin:false,
	constructor: function(obj){
		//初始化
		dojo.mixin(this,obj);
		var that = this;
		
		this.commentTextArea = dojo.byId(obj.textAreaId);
		this.commentsStore = new dojo.data.ItemFileWriteStore(picCommentTemplate);
		var submit = dojo.byId(this.submitBtnId);
		dojo.connect(submit, "onclick", dojo.hitch(this,"_addCommentToServer"));
		
		//i18n 
		var messages1= dojo.i18n.getLocalization("dojot", "common",dojo.locale);
		var messages2= dojo.i18n.getLocalization("dojot", "comment",dojo.locale);
		this._messages = dojo.mixin({},messages1,messages2);
		var commentUrl = dojo.moduleUrl("dojot.comment", "resources/comment.html");
		
		this.tpl = new dojox.dtl.Template(commentUrl);

		//增加删除评论函数到全局变量中。
		dojo.global["deleteComment"] = dojo.hitch(this,"_deleteCommentToServer");
	
		//国际化错误信息
		dojo.forEach(["emptyCommentErrorInfo","overlengthCommentErrorInfo","errorInfo","forbiddenCommentErrorInfo"], function(prop){
			if(!this[prop]){ this[prop] = this._messages[prop]; }
		}, this);
		
		//绑定分页事件
		dojo.global["showPage"] = dojo.hitch(this,"showPage");
	},
	showAllComments: function(picId){
		console.log("showAllComments-----------》"+picId+this.commentListUrl);
		this.picId = picId;
		var that = this;
		var _handleItem = function(item){
			//如果找到了则显示,没有则从服务器去拿
			if(item){
				that._showItem(item);
			}else{
				dojo.xhrGet({
					url: that.commentListUrl+"?picId="+picId,
					load:_loadItem,
					error:dojo.hitch(that,"_errorHandler"),
					handleAs: "json"
				});
			}
		};
		var _loadItem = function(item){
			that._addItemToStore(item,this._showItem);
		};
		var req = {
			identity:picId,
			onItem:_handleItem,
			onError:that._errorHandler
		};
		this.commentsStore.fetchItemByIdentity(req);
	},
	_addItemToStore: function(item,showItem){
		if(item){
			var newItem  = this.commentsStore.newItem(item);
			this.commentsStore.save();
			this._showItem(newItem);
		}	
	},
	_errorHandler: function(data){
		this.toggleTextArea(false);
		if(data &&  data.status == 403){
			this.suggestInfo(this.forbiddenCommentErrorInfo);
		}else{
			this.suggestInfo(this.errorInfo);
		}
		return;
	},
	_showItem: function(item){
		this.currentCommentItem = item;
		//add broswerCount
		this.addBroswerCountToStore(item);
		this.tplContext = new dojox.dtl.Context(item);
		this._setPageInfo();
		this._render();
		//dojo.fadeIn({node:reviewNode}).play(50); 
	},
	addBroswerCountToStore:function(item){
		var broswerCount = this.commentsStore.getValue(item,"browseCount");
		this.commentsStore.setValue(item,"browseCount",parseInt(broswerCount)+1);
		this.commentsStore.save();
	},
	addCommentCountToStore:function(item){
		
	},
	_addCommentToServer: function(){
		var isEmpty = this._isEmpty(this.commentTextArea.value);
		if(isEmpty){
			this.suggestInfo(this.emptyCommentErrorInfo);
			return;
		}
		
		var value = dojo.string.trim(this.commentTextArea.value);
		if(value.length > 50){
			this.suggestInfo(this.overlengthCommentErrorInfo);
			return;
		}
		this.toggleTextArea(true);
		var that = this;
		dojo.xhrPost({
			url: that.addCommentUrl,
			content:{
				picId:that.picId,
				desc:value,
				userId:that.viewId
			},
			load:function(data){
				console.log(data);
				that._addCommentToClient(data);
			},
			error:dojo.hitch(that,"_errorHandler"),
			handleAs: "json"
		});	
		
	},
	_addCommentToClient: function(comment){
		//add comment
		this.changeComment(function(comments){
			comments.splice(0,0,comment);
		},1)
		this.toggleTextArea(false);
	},
	_deleteCommentToServer: function(cId){
		if(confirm(this._messages.confirmDelete)){
			var that = this;
			dojo.xhrPost({
				url: that.delCommentUrl,
				content:{
					commentId: cId
				},
				load:function(data){
					that._deleteCommentFromClient(cId);
				},
				error:that._errorHandler,
				handleAs: "json"
			});	
		}
		
	},
	_deleteCommentFromClient:function(cId){
		//delete comment
		var that = this;
		this.changeComment(function(comments){
			var index = that._getCommentIndex(cId,comments);
			comments.splice(index,1);
		},-1);
	},
	_getUserName:function(){
		initPage();
		showPortrait('.portraitThumbComment','spic');
	},
	changeComment:function(fn,count){
		var comments = this.commentsStore.getValues(this.currentCommentItem,"picCommentList");
		//deal with comment, add or delete	
		fn(comments);
		this.commentsStore.setValues(this.currentCommentItem,"picCommentList",comments);
		//add comment count to store
		var commentCount = this.commentsStore.getValue(this.currentCommentItem,"commentCount");
		commentCount = parseInt(commentCount) + count;
		this.commentsStore.setValue(this.currentCommentItem,"commentCount",commentCount);
		//save
		this.commentsStore.save();
		this.tplContext.picCommentList = comments;
		this.tplContext.commentCount = commentCount;
		this._setPageInfo();
		this._render();
		this.commentTextArea.value = "";
	},
	_setPageInfo:function(){
		var req = {
			items:this.tplContext.picCommentList,
			isMemoryPage: true
		};
		var pageList = new dojot.util.MemoryPageList(req);
		console.log(pageList);
	
		this.tplContext.pageList = pageList;
	},
	_render:function(){
		
		dojo.publish("showPicExtraInfo",[this.tplContext]);
		//i18n
		var templateString = dojo.string.substitute(this.tpl.render(this.tplContext),{ 
				next: this._messages["next"],
				prev: this._messages["prev"],
				deleteComment: this._messages["deleteComment"]
		});
		//替换 amp 到 & 是因为在dojox.dtl 里面的.base的js的650行进行了替换，所以要替换回来
		templateString = templateString.deentityify().replace(/(<br\/>){1,}/g,"<br/>");

		this.reviewNode.innerHTML = templateString;
		this._getUserName();
		
		//初始用户访问控制显示
		dojot.security.isAccess("review");
	},
	_getCommentIndex:function(cId,comments){
		var i = 0;
		var com;
		for(var index in comments){
			com = comments[index];
			if(com.id == cId)return i;
			i++;
		}
		return undefined;
	},
	showPage: function(index){
		this.tplContext.pageList.showIndex(index);
		this._render();
	},
	toggleTextArea:function(flag){
		if(flag){
			dojo.attr(this.commentTextArea,"disabled",true)
		}else{
			dojo.attr(this.commentTextArea,"disabled",false)
		}
		//var attrDisabbled = dojo.attr(this.commentTextArea,"disabled");
		//attrDisabbled ?  dojo.attr(this.commentTextArea,"disabled",false) : dojo.attr(this.commentTextArea,"disabled",true);
	    if(dojo.attr(this.commentTextArea,"disabled")){
	    	console.log("attrDisabbled");
	        dojo.style(this.commentTextArea , "background","#ffffe0");
	    }else{
	    	console.log("attrDisabbled fale");
	    	dojo.style(this.commentTextArea , "background","#ffffff");
	    }
	},
	suggestInfo:function(value){
		var node = dojo.byId("suggestInfo");
		node.innerHTML = value;
		var fadeIn = dojo.fx.wipeIn({
			node: node,
			duration: 500
		});
		var dadeOut = dojo.fadeOut({
			node: node,
			duration: 1000
		});
		
		var a1 = dojo.fx.chain([fadeIn, dadeOut]);
		
		dojo.connect(a1, "onBegin", function(){
			console.log("onBegin");
			dojo.style("suggestInfo", "opacity",1);
			console.log(dojo.byId("commentErrorInfo"));
		});
		a1.play();
	},
	_isEmpty: function(value){
			// summary: Checks for whitespace
			return /^\s*$/.test(value); // Boolean
	},
	//清空评论的内容,如果图片被删除，或者图片被转移走，我们需要清空这张图片的所有评论,就是从仓库里面删除我们的数据
	//这步其实可以不做，但是为了节省空间，先加上
	cleanComment: function(picId){
		var that = this;
		var _deleteItem = function(item){
			if(item){
				that.commentsStore.deleteItem(item);
				that.commentsStore.save();
			}
		}
		var req = {
			identity:picId,
			onItem:_deleteItem,
			onError:that._errorHandler
		};
		this.commentsStore.fetchItemByIdentity(req);
		this.reviewNode.innerHTML = "";
	}
});
